package com.yinhe.music.yhmusic.base;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;

import com.apkfuns.logutils.LogUtils;
import com.hwangjr.rxbus.RxBus;
import com.yinhe.music.common.utils.ImageUtils;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.log.MLog;
import com.yinhe.music.yhmusic.utils.FileUtils;
import com.yinhe.music.yhmusic.utils.ViewUtils;

import java.io.File;
import java.io.IOException;

import static com.yinhe.music.yhmusic.constants.IConstants.CHOOSE_PHOTO;
import static com.yinhe.music.yhmusic.constants.IConstants.CROP_PHOTO;
import static com.yinhe.music.yhmusic.constants.IConstants.IMAGE_PATH;
import static com.yinhe.music.yhmusic.constants.IConstants.TAKE_PHOTO;

/**
 * @author 何晓华
 * 拍照或者选择相册图片
 */
public abstract class BaseTakePhotoActivity extends BaseServiceActivity {
    public Uri imageUri;
    public Uri outputUri;
    public ProgressDialog dialog;

    private static final String IMAGE_TYPE = "image/*";

    public String fileName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RxBus.get().register(this);
        dialog = ViewUtils.showWaitingDialog(this, "上传中，请稍后。。。", null, false);
    }

    public void getPhoto() {
        imageUri = Uri.fromFile(createFile());
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            intent.setAction(Intent.ACTION_PICK);
        } else {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        }

        //开启选择呢绒界面
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_TYPE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, CHOOSE_PHOTO);
    }


    public void takePhoto() {
        File imageFile = createFile();
        imageUri = Uri.fromFile(imageFile);
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            //通过FileProvider创建一个content类型的Uri
            imageUri = FileProvider.getUriForFile(this, IConstants.FILE_PROVIDER, imageFile);
        }
        intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO);
    }

    private File createFile() {
        fileName = FileUtils.getFileName() + ".jpg";
        File imageFile = new File(IMAGE_PATH, fileName);
        try {
            if (imageFile.exists()) {
                imageFile.delete();
            }
            imageFile.createNewFile();
        } catch (IOException e) {
            LogUtils.e(e);
        }
        return imageFile;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            // 从拍照界面返回
            case TAKE_PHOTO:
                MLog.debug("TAKE_PHOTO", "code:" + resultCode);
                finishTakePhoto(resultCode);
                break;
            // 从裁剪界面返回
            case CROP_PHOTO:
                MLog.debug("CROP_PHOTO", "code:" + resultCode);
                finishCropPhoto(resultCode);
                break;
            case CHOOSE_PHOTO:
                MLog.debug("CHOOSE_PHOTO", "code:" + resultCode);
                finishChoose(resultCode, data);
                break;
            default:
                break;
        }
    }

    private void finishTakePhoto(int resultCode) {
        if (resultCode == RESULT_OK) {
            //此处启动裁剪程序
            Intent intent = new Intent("com.android.camera.action.CROP");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                outputUri = Uri.fromFile(new File(IMAGE_PATH, fileName));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            } else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
            intent.setDataAndType(imageUri, IMAGE_TYPE);
            intent.putExtra("scale", true);
            intent.putExtra("aspectX", 1);  //裁剪框比例
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 400);//输出图片大小
            intent.putExtra("outputY", 400);
            startActivityForResult(intent, CROP_PHOTO);
        }
    }

    private void finishCropPhoto(int resultCode) {
        if (resultCode == RESULT_OK) {
            try {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(outputUri));
                    ImageUtils.saveBitmap(ImageUtils.resizeImage(bitmap, 300, 300), IMAGE_PATH, fileName);
                } else {
                    Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                            .openInputStream(imageUri));
                    ImageUtils.saveBitmap(ImageUtils.resizeImage(bitmap, 300, 300), IMAGE_PATH, fileName);
                }
                File file = new File(IMAGE_PATH, fileName);
                updateImage(file);
            } catch (IOException e) {
                LogUtils.e(e);
            }
        }
    }

    private void finishChoose(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            Intent intent = new Intent("com.android.camera.action.CROP");
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                outputUri = Uri.fromFile(new File(IMAGE_PATH, fileName));
                intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
            } else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            }
            intent.setDataAndType(data.getData(), IMAGE_TYPE);
            intent.putExtra("scale", true);
            intent.putExtra("aspectX", 1);  //裁剪框比例
            intent.putExtra("aspectY", 1);
            intent.putExtra("outputX", 400);//输出图片大小
            intent.putExtra("outputY", 400);
            startActivityForResult(intent, CROP_PHOTO);
        }
    }

    public abstract void updateImage(File file);

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        super.onDestroy();
    }
}
